<?php

use Biz\model\brandActivity\UserAddressModel;
use Biz\model\NewProduct\NewProductWinnerListModel;
use Hhz\AdministrativeRegion\Region;
use Biz\cache\brand\BrandShowActivity;

/**
 * Description: 创建收货地址
 * Created by PhpStorm.
 * User: 玉坤
 * Date: 2021/6/16
 * Time: 14:33
 */
class CreateAddressAction extends ActionPlugin
{
    public const USER_LEVEL = self::LEVEL_REGISTER;

    //参数校验-规则
    public const VALIDATOR_RULES = [
        'name' => 'require',
        'tel' => 'require',
        'address' => 'require',
        'area_code' => 'require|integer',
        'nid' => 'require|integer',
    ];

    public function main()
    {
        $uid = $this->uid;
        if (!$uid) {
            throw new \Exception("请登录重试！");
        }
        $name = $this->params['name'];
        $tel = $this->params['tel'];
        $area = $this->params['area_code'];
        $address = $this->params['address'];
        $nid = $this->params['nid'];
        $key = "new_product_address_" . $uid;
        $isLock = BrandShowActivity::isLock($key, 5);
        if ($isLock) {
            throw new \UnexpectedValueException('请不要频繁提交');
        }

        $info = NewProductWinnerListModel::first(['nid' => $nid, 'uid' => $uid], ['uid', 'type', 'nid']);
        if (!$info) {
            throw new \Exception('您未参加此活动');
        }
        $address_id = UserAddressModel::first(['uid' => $uid], 'id');
        try {
            $tel = UserAddressModel::encryptPhone($tel);
        } catch (\Exception $e) {
            throw new \Exception('手机号添加失败！，请重试');
        }
        $data['uid'] = $uid;
        $data['tel'] = $tel;
        $data['name'] = $name;
        $data['area_code'] = $area;
        $data['area_name'] = Region::getAreaDetailByCode($area);
        $data['address'] = $address;
        if ($address_id) {
            UserAddressModel::update($data, ['id' => $address_id]);
            $id = $address_id;
        } else {
            UserAddressModel::insert($data);
            $id = UserAddressModel::id();
        }
        if (!$id) {
            throw new \Exception('添加失败！，请重试');
        }
        $up_data['address_id'] = $id;
        $up_data['winner_status'] = NewProductWinnerListModel::NOT_SEND_PRIZE;
        $up_where['uid'] = $uid;
        $up_where['nid'] = $nid;
        NewProductWinnerListModel::update($up_data, $up_where);
        $this->setSuccess(['msg' => 'success']);

    }


}